<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="次卡名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入次卡名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关联项目" prop="shopItemId">
        <el-select
          v-model="queryParams.shopItemId"
          placeholder="请选择关联项目"
          clearable
          filterable
          style="width: 180px"
        >
          <el-option
            v-for="opt in shopItemOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          style="width: 160px"
        >
          <el-option
            v-for="opt in statusOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain :icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain :icon="Edit" :disabled="!selectedRows.length" @click="handleEdit">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="Delete"
          :disabled="!selectedRows.length"
          @click="handleBatchDelete"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain :icon="Download" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="70" align="center" :index="indexMethod" />
      <el-table-column label="次卡ID" prop="id" width="90" align="center" />
      <el-table-column label="次卡名称" prop="name" min-width="200" />
      <el-table-column label="次卡有效期" width="120" align="center">
        <template #default="{ row }">
          {{ row.day || 0 }}天
        </template>
      </el-table-column>
      <el-table-column label="关联项目" prop="shopItemName" min-width="140" />
      <el-table-column label="项目分类" prop="goodsTypeName" min-width="140" />
      <el-table-column label="次卡次数" width="100" align="center">
        <template #default="{ row }">
          {{ row.num || 0 }}次
        </template>
      </el-table-column>
      <el-table-column label="次卡价格" width="120" align="center">
        <template #default="{ row }">
          {{ formatPrice(row.price) }} 元
        </template>
      </el-table-column>
      <el-table-column label="上架状态" width="110" align="center">
        <template #default="{ row }">
          <el-tag :type="statusType(row.status)">
            {{ statusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="170" align="center">
        <template #default="{ row }">
          {{ parseTime(row.updateTime || row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" align="center" fixed="right">
        <template #default="{ row }">
          <el-button
            v-if="row.status === '01'"
            type="text"
            style="color: var(--el-color-warning)"
            @click="handleDown(row)"
          >
            下架
          </el-button>
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" style="color: var(--el-color-danger)" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog class="card-dialog" :title="dialogTitle" v-model="dialogVisible" width="780px" @close="onDialogClose">
      <el-form ref="formRef" class="card-form" :model="form" :rules="rules" label-width="110px">
        <div class="card-form-grid">
          <el-form-item label="次卡名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入次卡名称" />
          </el-form-item>
          <el-form-item label="次卡有效期" prop="day">
            <el-input-number v-model="form.day" :min="0" :step="1" style="width: 100%" placeholder="请输入天数" />
          </el-form-item>
          <el-form-item label="关联项目" prop="shopItemId">
            <el-select v-model="form.shopItemName" placeholder="请选择关联项目" filterable style="width: 100%" @change="onShopItemChange">
              <el-option
                v-for="opt in shopItemOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="次卡次数" prop="num">
            <el-input-number v-model="form.num" :min="0" :step="1" style="width: 100%" placeholder="请输入次数" />
          </el-form-item>
          <el-form-item label="次卡价格" prop="price">
            <el-input-number v-model="form.price" :min="0" :precision="2" :step="1" style="width: 100%" placeholder="请输入价格" />
          </el-form-item>
          <el-form-item label="上架状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
              <el-option v-for="opt in statusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="项目分类" prop="goodsTypeId">
            <el-select v-model="form.goodsTypeName" placeholder="请选择项目分类" filterable style="width: 100%" @change="onGoodsTypeChange">
              <el-option v-for="opt in goodsTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="次卡简介" prop="introduction" class="full-row">
            <el-input
              v-model="form.introduction"
              type="textarea"
              :rows="3"
              maxlength="200"
              show-word-limit
              placeholder="请输入次卡简介"
            />
          </el-form-item>
        </div>

        <el-row :gutter="16" class="upload-row full-row">
          <el-col :span="12">
            <el-form-item label="次卡头图" prop="headImg" class="upload-item">
              <el-upload
                class="upload-card"
                drag
                :action="uploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                :on-success="res => handleUploadSuccess('headImg', res)"
                :on-error="handleUploadError"
              >
                <div v-if="form.headImg" class="upload-preview">
                  <img :src="resolveImageUrl(form.headImg)" alt="head" />
                  <div class="upload-mask">点击重新上传</div>
                </div>
                <div v-else class="upload-placeholder">
                  <span class="upload-icon">TM</span>
                  <p>点击或拖拽上传</p>
                  <small>支持 png/jpg/jpeg，≤5MB</small>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详情图片" prop="detailsImg" class="upload-item">
              <el-upload
                class="upload-card"
                drag
                :action="uploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                :on-success="res => handleUploadSuccess('detailsImg', res)"
                :on-error="handleUploadError"
              >
                <div v-if="form.detailsImg" class="upload-preview">
                  <img :src="resolveImageUrl(form.detailsImg)" alt="detail" />
                  <div class="upload-mask">点击重新上传</div>
                </div>
                <div v-else class="upload-placeholder">
                  <span class="upload-icon">TM</span>
                  <p>点击或拖拽上传</p>
                  <small>支持 png/jpg/jpeg，≤5MB</small>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="次卡详情" prop="details" class="full-row">
          <Editor v-model="form.details" :minHeight="220" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BaseNumberCardIndex">
import { nextTick, onMounted, reactive, ref, toRefs } from 'vue'
import { Search, Refresh, Plus, Edit, Delete, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addBaseNumberCard, delBaseNumberCard, handleCardDown, listBaseNumberCard, updateBaseNumberCard } from '@/api/system/baseNumberCard'
import { listGoodType } from '@/api/system/goodType'
import { listShopItem } from '@/api/system/shopItem'
import { download } from '@/utils/request'
import { parseTime } from '@/utils/ruoyi'
import { getToken } from '@/utils/auth'

const queryFormRef = ref()
const formRef = ref()
const state = reactive({
  loading: true,
  showSearch: true,
  total: 0,
  list: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    shopItemId: undefined,
    status: undefined
  }
})

const { loading, showSearch, total, list, queryParams } = toRefs(state)
const shopItemOptions = ref([])
const goodsTypeOptions = ref([])
const statusOptions = [
  { label: '上架', value: '01', type: 'success' },
  { label: '下架', value: '00', type: 'info' },
  { label: '已停用', value: '02', type: 'warning' }
]
const selectedRows = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const form = ref(createDefaultForm())
const baseApi = import.meta.env.VITE_APP_BASE_API
const uploadUrl = `${baseApi}/common/upload`
const uploadHeaders = { Authorization: 'Bearer ' + getToken() }
const rules = {
  name: [{ required: true, message: '请输入次卡名称', trigger: 'blur' }],
  shopItemId: [{ required: true, message: '请选择关联项目', trigger: 'change' }],
  day: [{ required: true, message: '请输入有效天数', trigger: 'change' }],
  num: [{ required: true, message: '请输入次数', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  goodsTypeId: [{ required: true, message: '请选择项目分类', trigger: 'change' }],
  headImg: [{ required: true, message: '请上传次卡头图', trigger: 'change' }],
  detailsImg: [{ required: true, message: '请上传详情图片', trigger: 'change' }],
  details: [{ required: true, message: '请输入次卡详情', trigger: 'blur' }]
}

function createDefaultForm() {
  return {
    id: undefined,
    name: '',
    shopItemId: undefined,
    shopItemName: '',
    goodsTypeId: undefined,
    goodsTypeName: '',
    day: 0,
    num: 0,
    price: 0,
    status: '01',
    introduction: '',
    headImg: '',
    detailsImg: '',
    details: ''
  }
}

function getList() {
  loading.value = true
  listBaseNumberCard(queryParams.value)
    .then(res => {
      list.value = res.rows || []
      total.value = res.total || 0
    })
    .finally(() => {
      loading.value = false
    })
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

function handleSelectionChange(rows) {
  selectedRows.value = rows || []
}

function indexMethod(index) {
  const p = queryParams.value || {}
  const pageNum = Number(p.pageNum || 1)
  const pageSize = Number(p.pageSize || 10)
  return (pageNum - 1) * pageSize + index + 1
}

function formatPrice(val) {
  return (Number(val) || 0).toFixed(2)
}

function statusLabel(value) {
  const it = statusOptions.find(opt => String(opt.value) === String(value))
  return it ? it.label : '未知'
}

function statusType(value) {
  const it = statusOptions.find(opt => String(opt.value) === String(value))
  return it?.type
}

function openDialog(row) {
  dialogTitle.value = row?.id ? '编辑次卡' : '新增次卡'
  form.value = { ...createDefaultForm(), ...row }
  syncGoodsTypeName()
  dialogVisible.value = true
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

function handleAdd() {
  openDialog()
}

function handleEdit(row) {
  const target = row || selectedRows.value[0]
  if (!target) {
    ElMessage.warning('请先选择要编辑的次卡')
    return
  }
  openDialog(target)
}

function handleDelete(row) {
  const ids = row ? [row.id] : selectedRows.value.map(item => item.id).filter(Boolean)
  if (!ids.length) {
    ElMessage.warning('请先选择要删除的次卡')
    return
  }
  ElMessageBox.confirm(`确认删除选中的 ${ids.length} 条次卡吗？`, '提示', { type: 'warning' })
    .then(() => {
      loading.value = true
      return delBaseNumberCard(ids)
    })
    .then(() => {
      ElMessage.success('删除成功')
      getList()
    })
    .finally(() => {
      loading.value = false
    })
}

function handleBatchDelete() {
  handleDelete()
}

function handleDown(row) {
  if (!row?.id) return
  ElMessageBox.confirm(`确认将【${row.name}】下架吗？`, '提示', { type: 'warning' })
    .then(() => {
      loading.value = true
      return handleCardDown(row.id)
    })
    .then(() => {
      ElMessage.success('下架成功')
      getList()
    })
    .finally(() => {
      loading.value = false
    })
}

function handleExport() {
  download(
    '/goods/BaseNumberCard/export',
    { ...queryParams.value },
    `次卡列表_${Date.now()}.xlsx`
  )
}

function submitForm() {
  formRef.value?.validate(valid => {
    if (!valid) return
    submitLoading.value = true
    const payload = { ...form.value }
    const requestFn = payload.id ? updateBaseNumberCard : addBaseNumberCard
    requestFn(payload)
      .then(() => {
        ElMessage.success(payload.id ? '修改成功' : '新增成功')
        dialogVisible.value = false
        getList()
      })
      .finally(() => {
        submitLoading.value = false
      })
  })
}

function onDialogClose() {
  form.value = createDefaultForm()
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

function onShopItemChange(val) {
  const opt = shopItemOptions.value.find(item => String(item.value) === String(val))
  if (opt) {
    form.value.shopItemName = opt.label
  }
}

function onGoodsTypeChange(val) {
  // 确保值存在且有效
  if (val === undefined || val === null || val === '') {
    form.value.goodsTypeName = ''
    return
  }
  
  // 查找对应的选项并更新名称
  const opt = goodsTypeOptions.value.find(item => String(item.value) === String(val))
  if (opt && opt.label) {
    form.value.goodsTypeName = opt.label
  } else {
    // 如果找不到匹配项，尝试重新加载选项后再查找
    loadGoodsTypeOptions().then(() => {
      const retryOpt = goodsTypeOptions.value.find(item => String(item.value) === String(val))
      if (retryOpt) {
        form.value.goodsTypeName = retryOpt.label
      }
    })
  }
}

function loadShopItemOptions() {
  listShopItem({ pageNum: 1, pageSize: 999 })
    .then(res => {
      const rows = res?.rows || []
      shopItemOptions.value = rows.map(r => ({
        label: r.itemName || r.projectName || r.name,
        value: r.id
      }))
    })
    .catch(() => {
      shopItemOptions.value = []
    })
}

function loadGoodsTypeOptions() {
  return listGoodType({ pageNum: 1, pageSize: 999 })
    .then(res => {
      const rows = res?.rows || []
      goodsTypeOptions.value = rows.map(r => ({
        label: r.typeName || r.name,
        value: r.id
      }))
      syncGoodsTypeName()
      return res
    })
    .catch(() => {
      goodsTypeOptions.value = []
      return null
    })
}

function syncGoodsTypeName() {
  const currentId = form.value.goodsTypeId
  if (!currentId) return
  const opt = goodsTypeOptions.value.find(item => String(item.value) === String(currentId))
  if (opt) {
    form.value.goodsTypeName = opt.label
  }
}

function handleUploadSuccess(field, res) {
  if (res.code === 200) {
    const url = res.url || res.fileName || res.data?.url
    form.value[field] = url
    ElMessage.success('上传成功')
    formRef.value?.validateField(field)
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}

function handleUploadError() {
  ElMessage.error('上传失败，请重试')
}

function beforeImageUpload(file) {
  const isImage = ['image/png', 'image/jpeg', 'image/jpg'].includes(file.type)
  if (!isImage) {
    ElMessage.error('仅支持 png/jpg/jpeg 格式')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB')
    return false
  }
  return true
}

function resolveImageUrl(url) {
  if (!url) return ''
  if (/^https?:\/\//.test(url)) return url
  if (url.startsWith('/')) {
    return `${baseApi}${url}`
  }
  return `${baseApi}/${url}`
}

onMounted(() => {
  loadShopItemOptions()
  loadGoodsTypeOptions()
  getList()
})
</script>

<style scoped lang="scss">
.card-dialog :deep(.el-dialog__body) {
  padding: 12px 24px 10px;
  background: #f7f8fa;
}

.card-form {
  background: #fff;
  border-radius: 12px;
  padding: 12px 20px 4px;
}

.card-form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
  gap: 12px 24px;
}

.card-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.card-form .full-row {
  grid-column: 1 / -1;
}

.upload-row {
  width: 100%;
}

.upload-item {
  width: 100%;
}

.upload-card {
  width: 100%;
  border-radius: 12px;
  overflow: hidden;
}

.upload-card :deep(.el-upload) {
  width: 100%;
}

.upload-card :deep(.el-upload-dragger) {
  padding: 0;
  border-radius: 12px;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 180px;
  border: 1px dashed #c0c4cc;
  border-radius: 12px;
  color: #909399;
  background: #fafafa;
}

.upload-placeholder .upload-icon {
  font-size: 28px;
  color: #c0c4cc;
  margin-bottom: 8px;
}

.upload-placeholder p {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.upload-placeholder small {
  margin-top: 4px;
  color: #909399;
}

.upload-preview {
  position: relative;
  width: 100%;
  height: 180px;
  border-radius: 12px;
  overflow: hidden;
}

.upload-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-mask {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.35);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
  font-size: 14px;
}

.upload-preview:hover .upload-mask {
  opacity: 1;
}
</style>
